package com.yangziqiang.task;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yangziqiang.entity.EsMovies;
import com.yangziqiang.mapper.MoviesRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @ClassName MySechdule
 * @Description TODO
 * @Author 18516
 * @DATE 2022/2/10 09:12:28
 * @Version 1.0
 */
@Component
public class MyScheduled {


    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    KafkaTemplate kafkaTemplate;

    @Autowired
    MoviesRepository moviesRepository;

    @Scheduled(cron = "* 0/5 * ? * *")
    public void myTask() {
        ValueOperations forValue = redisTemplate.opsForValue();
//        模糊获取redis中的所有keys
        Set keys = redisTemplate.keys("updMovies:*");
        if (keys != null) {
            //  有值，进行消息补偿，redisKey是redis中存的key
            keys.forEach(redisKey -> {
//                获取对应key中的map
                Map entries = redisTemplate.opsForHash().entries(redisKey);
                Long movieTime = (Long) entries.get("movieTime");
                long now = System.currentTimeMillis();
                if (now - movieTime > 1000 * 60 * 5) {
                    Object movieJson = entries.get("movieJson");
                    EsMovies esMovies = JSON.parseObject(movieJson.toString(), EsMovies.class);
                    moviesRepository.save(esMovies);
                    redisTemplate.delete(redisKey);
                }
            });

        }
    }
}

